package com.learn.multDataSource.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * 配置搜索库的SqlSessionFactory和SqlSessionTemplate
 *
 * 扫描对应的 Mapper接口并容器管理
 */
@Configuration
@MapperScan(basePackages = SecondDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "secondSqlSessionFactory")
public class SecondDataSourceConfig {
    // 精确到 master 目录，以便跟其他数据源隔离
    static final String PACKAGE = "com.learn.multDataSource.mapper.elastic";
    private static final String MAPPER_LOCATION = "mybatis/mapper/elastic/*.xml";

    /**
     * SqlSessionFactory
     */
    @Bean(name = "secondSqlSessionFactory")
    public SqlSessionFactory clusterSqlSessionFactory(@Qualifier("secondDataSource") DataSource secondDataSource) throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(secondDataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(SecondDataSourceConfig.MAPPER_LOCATION));
        return sessionFactory.getObject();
    }

    /**
     * SqlSessionTemplate
     */
    @Bean(name = "secondSqlSessionTemplate")
    public SqlSessionTemplate setSqlSessionTemplate(@Qualifier("secondSqlSessionFactory") SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }



//    由于不支持多数据源事务一致性，由 JTA + Atomikos 配置取代
//    @Bean(name = "secondDataSource")
//    @ConfigurationProperties(prefix = "spring.datasource.second")
//    public DataSource master2DataSource() {
//        return new DruidDataSource();
//    }
//
//    @Bean(name = "secondTransactionManager")
//    public DataSourceTransactionManager master2TransactionManager(@Qualifier("secondDataSource") DataSource secondDataSource) {
//        return new DataSourceTransactionManager(secondDataSource);
//    }
}
